Imports System.Web
Imports System.Globalization
Imports System.Threading
Imports System.Web.SessionState
Imports MyFramework
Imports MIMS_WRS.Web.Schedules

Public Class [Global]
    Inherits System.Web.HttpApplication

#Region " Component Designer Generated Code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        

    End Sub

    'Required by the Component Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Component Designer
    'It can be modified using the Component Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

#End Region

    Private timer As Timers.Timer
    Private schedulerThread As System.Threading.Thread = Nothing

    Private lastRunWeek As Int32 = -1

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        Logger.Info("Application Start at " + DateTime.Now.ToString())

        '      Dim config As SchedulerConfiguration = New SchedulerConfiguration(60000 * config.TimerInterval)
        '      config.Jobs.Add(New SendDocNotReceivedMailJob)
        '      Dim m_scheduler As Scheduler = New Scheduler(config)
        'System.Threading.ThreadStart myThreadStart =
        '  new System.Threading.ThreadStart(scheduler.Start);
        'schedulerThread = new System.Threading.Thread(myThreadStart);
        'schedulerThread.Start();


        timer = New System.Timers.Timer(60000 * Config.TimerInterval)
        AddHandler timer.Elapsed, AddressOf timer_Elapsed
        'Only raise the event the first time Interval elapses.
        timer.AutoReset = True
        timer.Enabled = Config.EnableScheduling

        Logger.Info(String.Format("Timer was started at {0} with interval {1} minute(s)", DateTime.Now.ToString(), Config.TimerInterval))
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim cultureName As String = Config.Culture
        Dim ci As CultureInfo = New CultureInfo(cultureName)
        Thread.CurrentThread.CurrentCulture = ci
        Thread.CurrentThread.CurrentUICulture = ci

        If Request.Url.AbsoluteUri.ToLower().IndexOf("orderlist.aspx") > -1 Then
            Response.Filter = New WhitespaceFilter(Response.Filter)
        End If
    End Sub

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
        Dim unhandledEx As Exception = Server.GetLastError

        MyFramework.Logger.Error("Unhandled error", unhandledEx)

        Dim errorLevel As Integer
        Try
            errorLevel = CInt(System.Configuration.ConfigurationSettings.AppSettings("MIMS_WRS.ErrorPage.Level"))
        Catch ex As Exception
            errorLevel = -2
        End Try

        If errorLevel > -2 Then
            If TypeOf (unhandledEx) Is System.Security.SecurityException Then
                Response.Redirect(Config.AppRoot & "/Errors/AuthError.aspx")
                Server.ClearError()
            ElseIf TypeOf (unhandledEx) Is HttpRequestValidationException Then
                Server.Transfer(Config.AppRoot & "/Errors/ValidateError.aspx")
            ElseIf TypeOf (unhandledEx.InnerException) Is ApplicationException _
                 Or TypeOf (unhandledEx.InnerException.GetBaseException) Is ApplicationException Then
                Server.Transfer(Config.AppRoot & "/Errors/AppError.aspx")
            ElseIf TypeOf (unhandledEx.InnerException) Is System.Data.SqlClient.SqlException Then
                Server.Transfer(Config.AppRoot & "/Errors/SqlError.aspx")
            Else
                Server.Transfer(Config.AppRoot & "/Errors/DefaultError.aspx")
            End If
        End If
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application ends
        Logger.Info("Application End at " + DateTime.Now.ToString())
    End Sub

    Private Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        ' stop timer
        'timer.Stop()
        'timer.Enabled = False

        Dim currentWeek As Int32 = DatePart(DateInterval.WeekOfYear, DateTime.Now.AddDays(-1))

        If (currentWeek <> lastRunWeek AndAlso DateTime.Now.DayOfWeek = Config.ScheduleDate _
            AndAlso DateTime.Now.Hour = Config.ScheduleHour AndAlso RequestContext.CurrentOffice.NotifyEmailEnable) Then
            lastRunWeek = currentWeek

            Logger.Info("Begin sending mail at " + DateTime.Now.ToString())

            'Dim fromEmail As String = Config.AdminEmail
            Dim toEmail As String = Config.ReceiverEmails

            ' check for " If Payment not at Full Paid or L/C Paid or at Credit after 2 weeks from Shipped Date"
            MIMS_WRS.Web.Components.MailService.CheckAndSendPaymentNotPaidMail()

            ' check for "documents Doc Received is still blank within one week of ETA date "
            MIMS_WRS.Web.Components.MailService.CheckAndSendDocNotReceivedMail()

            ' check for "the ETA has past by 1 week"
            MIMS_WRS.Web.Components.MailService.CheckAndSendETAHasPastMail()

            Logger.Info("End of sending mail at " + DateTime.Now.ToString())
        End If

        Logger.Info("check for out-of-date reserved quantity start at " + DateTime.Now.ToString())
        ' check for out-of-date reserved quantity
        BOService.CheckOutOfDateReservedQuantity()
        Logger.Info("check for out-of-datereserved quantity completed at " + DateTime.Now.ToString())

        ' re enable timer
        'timer.Enabled = True
        'timer.Start()
    End Sub
End Class
